package com.example.kotlinlearningproject.utils

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import java.io.UnsupportedEncodingException
import java.lang.reflect.InvocationTargetException
import java.net.NetworkInterface
import java.util.UUID

private const val TAG = "DeviceIdUtil";
class DeviceIdUtil {
    companion object {

        /**
         * 获取 MEID
         */
        @SuppressLint("PrivateApi")
        @JvmStatic
        fun getMEID(): String {
            try {
                val clazz = Class.forName("android.os.SystemProperties")
                val method = clazz.getMethod("get", String::class.java, String::class.java)

                val meid = method.invoke(null, "ril.cdma.meid", "") as String
                if (!TextUtils.isEmpty(meid) && !"unknown".equals(meid)) {
                    return meid
                }
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
                Log.w("MEID", "getMEID error : " + e.message)
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
                Log.w("MEID", "getMEID error : " + e.message)
            } catch (e: InvocationTargetException) {
                e.printStackTrace()
                Log.w("MEID", "getMEID error : " + e.message)
            } catch (e: ClassNotFoundException) {
                e.printStackTrace()
                Log.w("MEID", "getMEID error : " + e.message)
            }
            return ""
        }

        /**
         * 获取 MAC 地址
         */
        @JvmStatic
        fun getMacAddress(context: Context): String {
            var result: String = ""
            try {
                val networkInterface = NetworkInterface.getByName("wlan0")
                val hardwareAddress = networkInterface.hardwareAddress

                val buffer = StringBuffer()
                for ((index, value) in hardwareAddress.withIndex()) {
                    buffer.append(value)
                    if (index < hardwareAddress.size - 1) buffer.append(":")
                }
                result = buffer.toString()
            } catch (exception: Exception) {
                Log.w(TAG, "error : $exception")
            }
            return result
        }


        @SuppressLint("HardwareIds")
        fun getUniqueID(context: Context): String {
            var id: String? = null
            val androidId: String =
                Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
            if (!TextUtils.isEmpty(androidId) && "9774d56d682e549c" != androidId) {
                try {
                    val uuid = UUID.nameUUIDFromBytes(androidId.toByteArray(charset("utf8")))
                    id = uuid.toString()
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }
            }
            if (TextUtils.isEmpty(id)) {
                id = getUUID(context)
            }
            return if (TextUtils.isEmpty(id)) UUID.randomUUID().toString() else id!!
        }

        private fun getUUID(context: Context): String {
            var serial: String? = null
            val m_szDevIDShort =
                "35" + Build.BOARD.length % 10 + Build.BRAND.length % 10
            + (if (null != Build.CPU_ABI) Build.CPU_ABI.length else 0) % 10
            + Build.DEVICE.length % 10 + Build.DISPLAY.length % 10 + Build.HOST.length % 10
            + Build.ID.length % 10 + Build.MANUFACTURER.length % 10 + Build.MODEL.length % 10
            + Build.PRODUCT.length % 10 + Build.TAGS.length % 10 + Build.TYPE.length % 10
            + Build.USER.length % 10 //13 位
            serial = Build.UNKNOWN + UUID.randomUUID().toString() // 随便一个初始化

            //使用硬件信息拼凑出来的15位号码
            return UUID(m_szDevIDShort.hashCode().toLong(), serial.hashCode().toLong()).toString()
        }

        @SuppressLint("HardwareIds")
        fun getIMEIDeviceId(context: Context): String {
            val deviceId: String
            deviceId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
            } else {
                val mTelephony =
                    context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                if (context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return ""
                }
                if (mTelephony.deviceId != null) {
                    mTelephony.imei
                } else {
                    Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
                }
            }
            Log.d("deviceId", deviceId)
            return deviceId
        }
    }
}
